#pragma once

#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"
#include "nocopy.hpp"
#include "Comm.hpp"

const static int default_backlog = 5;

class TcpServer : public nocopy
{
public:
    TcpServer(uint16_t port)
        : _port(port), _isrunning(false)
    {
    }

    void Init()
    {
        _listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensock < 0)
        {
            lg.LogMessage(Fatal, "create socket error, errno code: %d, error string: %s\n", errno, strerror(errno));
            exit(Fatal);
        }
        lg.LogMessage(Debug, "create socket success, sockfd: %d\n", _listensock);

        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = htonl(INADDR_ANY);
        local.sin_family = AF_INET;

        if (bind(_listensock, CONV(&local), sizeof(local)))
        {
            lg.LogMessage(Fatal, "bind socket error, errno code: %d, error string: %s\n", errno, strerror(errno));
            exit(Bind_Err);
        }
        // 设置socket为监听状态，tcp特有的

        if (listen(_listensock, default_backlog) != 0)
        {
            lg.LogMessage(Fatal, "listen socket error, errno code: %d, error string: %s\n", errno, strerror(errno));
            exit(Listen_Err);
        }
        lg.LogMessage(Debug, "listen socket success, sockfd: %d\n", _listensock);
    }

     // Tcp 连接全双工通信的.
     void Service(int sockfd)
     {
        char buffer[1024];
        while(true)
        {
            ssize_t n=read(sockfd,buffer,sizeof(buffer));
            if(n>0)
            {

                buffer[n]=0;
                std::cout<<"client say#"<<buffer<<std::endl;
                std::string echo_string = "server echo# i got： ";
                echo_string += buffer;

                write(sockfd,echo_string.c_str(),echo_string.size());
            }
            else if(n==0)
            {
                lg.LogMessage(Info, "client quit...\n");
                break;

            }
            else
            {
                lg.LogMessage(Error, "read socket error, errno code: %d, error string: %s\n", errno, strerror(errno));
                break;
            }
        }
     }

     void Start()
     {
        _isrunning=true;
        while(_isrunning)
        {

            struct sockaddr_in peer;
            socklen_t len=sizeof(peer);

            int sockfd=accept(_listensock,CONV(&peer),&len);
             if (sockfd < 0)
            {
                lg.LogMessage(Warning, "accept socket error, errno code: %d, error string: %s\n", errno, strerror(errno));
                continue;
            }
            lg.LogMessage(Debug, "accept success, get n new sockfd: %d\n", sockfd);
            Service(sockfd);
            close(sockfd);

        }
     }

     ~TcpServer()
     {
        
     }

private:
    uint16_t _port;
    bool _isrunning;
    int _listensock;
};